package com.darren.framework.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.darren.framework.component.SystemParameterHelper;
import com.darren.framework.entity.AppSession;
import com.darren.framework.entity.LoginRecord;
import com.darren.framework.entity.LoginRecord.LoginType;
import com.darren.framework.entity.ResponseJSON;
import com.darren.framework.entity.TokenEntity;
import com.darren.framework.entity.User;
import com.darren.framework.service.LoginRecordService;
import com.darren.framework.service.UserService;
import com.darren.framework.utils.EncryptAESUtil;
import com.darren.framework.utils.JWTUtil;
import com.darren.framework.utils.StringUtil;

@Controller
@RequestMapping("/user")
public class UserAction extends BaseAction{
	
	private Logger logger = LogManager.getLogger(UserAction.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private LoginRecordService loginRecordService;
	
	@RequestMapping("/login")
	public String showSelectProduct(HttpServletRequest request){

		return "/backend/login";
	}

	@ResponseBody
    @RequestMapping(value = "/login/validate",method = RequestMethod.POST)
    public ResponseJSON login(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {
    	ResponseJSON responseJson = new ResponseJSON();
    	JSONObject jsonData = new JSONObject();
    	String userName = requestJson.getString("username");
    	String password = requestJson.getString("password");
    	if(StringUtil.isEmptyOrWhitespace(userName) || StringUtil.isEmptyOrWhitespace(password)){
    		responseJson.setStatus(1);
    		responseJson.setMessage("用户名或者密码不能为空。");
    	}else{
    		User user = userService.findByUserAccountOrMobile(userName);
    		password = EncryptAESUtil.getEncryption(password, SystemParameterHelper.getEncryptKey());
    		if(user == null){
    			responseJson.setStatus(2);
        		responseJson.setMessage("当前用户不存在。");
    		}else if(!password.trim().equals(user.getPassword())){
    			responseJson.setStatus(3);
        		responseJson.setMessage("密码不正确，请核对后再登陆。");
    		}else{
    			responseJson.setStatus(0);
        		responseJson.setMessage("登陆成功。");        		
        		LoginRecord loginRecord  = new  LoginRecord();
        		loginRecord.setLoginId(user.getId());
        		loginRecord.setLoginTime(new Date());
        		loginRecord.setLoginType(LoginType.USER.getDescription());
        		loginRecord.setExpiredTime(JWTUtil.getAccessExpired());
        		loginRecord.setDelete(false);

        		loginRecord = loginRecordService.save(loginRecord);
        		TokenEntity tokenEntity = new TokenEntity(loginRecord.getId());
        		String accessToken = JWTUtil.signAccessJWT(tokenEntity);
        		String refreshToken = JWTUtil.signRefreshJWT(tokenEntity);
        		Long expires_in = JWTUtil.getAccessExpired();
        		
        		AppSession appSession = new AppSession();
        		appSession.setAttribute("accessToken", accessToken);
    			appSession.setAttribute("refreshToken", refreshToken);			
    			try {
    				loginRecord.setApplicationSession(appSession);
    				loginRecord = loginRecordService.update(loginRecord);
    			} catch (Exception e) {
    				logger.error(e.getMessage(),e);
    			}
    			
    			jsonData.put("accessToken", accessToken);
    			jsonData.put("refreshToken", refreshToken);
    			jsonData.put("expiresIn", expires_in);
    			
    			response.setHeader("accessToken", accessToken);
    			response.setHeader("refreshToken", refreshToken);
    			response.setHeader("expiresIn", expires_in.toString());				
    			responseJson.setData(jsonData);
    		}
    	}
    	logger.info("==============================================================");
    	logger.info(requestJson.toString());
    	logger.info(responseJson.toString());
    	logger.info("==============================================================");
        return responseJson;
    }
	
}
